package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.Character;
import com.writing.entity.Novel;
import com.writing.service.CharacterService;
import com.writing.service.NovelService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 人物控制器
 */
@RestController
@RequestMapping("/novels/{novelId}/characters")
@RequiredArgsConstructor
public class CharacterController {

    private final CharacterService characterService;
    private final NovelService novelService;

    /**
     * 验证用户是否有权限访问小说
     */
    private boolean validateNovelAccess(Long novelId, Long userId) {
        Novel novel = novelService.getById(novelId);
        return novel != null && novel.getUserId().equals(userId);
    }

    /**
     * 获取小说的所有人物
     */
    @GetMapping
    public Result<List<Character>> getCharactersByNovelId(@PathVariable Long novelId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            List<Character> characters = characterService.getCharactersByNovelId(novelId);
            return Result.success(characters);
        } catch (Exception e) {
            return Result.error("获取人物列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取人物详情
     */
    @GetMapping("/{characterId}")
    public Result<Character> getCharacter(@PathVariable Long novelId,
                                        @PathVariable Long characterId,
                                        HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            Character character = characterService.getCharacterById(characterId, novelId);
            if (character == null) {
                return Result.error("人物不存在");
            }
            return Result.success(character);
        } catch (Exception e) {
            return Result.error("获取人物详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建人物
     */
    @PostMapping
    public Result<Character> createCharacter(@PathVariable Long novelId,
                                           @RequestBody Character character,
                                           HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            character.setNovelId(novelId);
            Character createdCharacter = characterService.createCharacter(character);
            return Result.success(createdCharacter);
        } catch (Exception e) {
            return Result.error("创建人物失败: " + e.getMessage());
        }
    }

    /**
     * 更新人物
     */
    @PutMapping("/{characterId}")
    public Result<Character> updateCharacter(@PathVariable Long novelId,
                                           @PathVariable Long characterId,
                                           @RequestBody Character character,
                                           HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            character.setId(characterId);
            character.setNovelId(novelId);
            Character updatedCharacter = characterService.updateCharacter(character);
            if (updatedCharacter == null) {
                return Result.error("人物不存在或无权限修改");
            }
            return Result.success(updatedCharacter);
        } catch (Exception e) {
            return Result.error("更新人物失败: " + e.getMessage());
        }
    }

    /**
     * 删除人物
     */
    @DeleteMapping("/{characterId}")
    public Result<Void> deleteCharacter(@PathVariable Long novelId,
                                      @PathVariable Long characterId,
                                      HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            boolean deleted = characterService.deleteCharacter(characterId, novelId);
            if (!deleted) {
                return Result.error("人物不存在或无权限删除");
            }
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除人物失败: " + e.getMessage());
        }
    }
}
